package com.lf.api.weixin;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.lf.api.Constants;
import com.lf.api.util.IFConfig;
import com.lf.api.weixin.entity.AccessToken;
import com.lf.api.weixin.entity.Button;
import com.lf.api.weixin.entity.CommonButton;
import com.lf.api.weixin.entity.Menu;
import com.lf.api.weixin.entity.ResultCode;
import com.lf.api.weixin.entity.WeiXinAccount;

public class MenuManager {
	private static Logger log = LoggerFactory.getLogger(MenuManager.class);

	public static void main(String[] args) throws UnsupportedEncodingException {
		AccessToken at = WeiXinUtil.getAccessToken(WeiXinAccount.TEST);
		if (null != at) {
			// 调用接口创建菜单
			ResultCode entity = WeiXinUtil.createMenu(getMenu(), at.getAccessToken());
			// 判断菜单创建结果
			if (entity.getErrorCode() == 0)
				log.info("菜单创建成功！");
			else
				log.info("菜单创建失败，错误码：" + JacksonUtil.bean2JSon(entity));
		}
	}

	/**
	 * 组装菜单数据
	 * 
	 * @return
	 * @throws UnsupportedEncodingException 
	 */
	private static Menu getMenu() throws UnsupportedEncodingException {
		String baseUrl = IFConfig.getValue("base_url", "http://127.0.0.1:8080/apiWeb");
		String url = Constants.WeiXinURL.OAUTH2_URL.replace("APPID", WeiXinAccount.TEST.getAppID());
		CommonButton btn11 = new CommonButton();
		btn11.setName("纷享精选");
		btn11.setType("view");
		btn11.setUrl(url.replace("REDIRECT_URI", URLEncoder.encode(baseUrl + "/subject/list/page", "UTF-8")));
		btn11.setKey("11");

		CommonButton btn12 = new CommonButton();
		btn12.setName("+说呗");
		btn12.setType("view");
		btn12.setUrl(url.replace("REDIRECT_URI", URLEncoder.encode(baseUrl + "/subject/form/page", "UTF-8")));
		btn12.setKey("12");

		CommonButton btn13 = new CommonButton();
		btn13.setName("我的");
		btn13.setType("view");
		btn13.setUrl(url.replace("REDIRECT_URI", URLEncoder.encode(baseUrl + "/user/center", "UTF-8")));
		btn13.setKey("13");

		/**
		 * 封装整个菜单
		 */
		Menu menu = new Menu();
		menu.setButton(new Button[] { btn11, btn12, btn13 });

		return menu;
	}
}